<?php

include_once "notesrack.php";


if ( empty ( $_GET ) ) {
	get_header( "All notes", "Showing all public notes from everyone, and all your notes.");
	$notes = get_notes( "all_notes" );
	
	echo htmlize_notes( $notes, "all_notes" );		
	
	get_footer();
}

if ( isset($_GET) and isset( $_GET['get_suggestions'] ) and isset( $_GET['query_string'] ) ) {
	$response = "";
	for( $s = 0; $s <= 2; $s++ ) {
		$s_note_url = get_note_url($s);
		$s_note_title = get_note_title($s);
		$r = sprintf('<a href="%s">%s</a>', $s_note_url, $s_note_title );		
	}
}


if ( isset($_GET) and isset( $_GET['view_note'] ) and ! empty( $_GET['note_id'] ) ) {
	get_header("View note","View note");
	$notes_array = array();
	array_push( $notes_array, get_notes_by_id( $_GET['note_id'] ) );
	htmlize_notes( $notes_array, "all_notes" );
	get_footer();
}


if ( isset($_GET) and !empty ( $_GET['q'] ) and count( $_GET ) == 1 ) {
	
	$search_text = htmlspecialchars( $_GET['q'] );
		
	$notes = search_notes ( $search_text );
	get_header( sprintf("Search results for: %s", $search_text ),  sprintf("Search results for: %s", $search_text ) );
	htmlize_notes( $notes, "all_notes" );
	get_footer();
}

if ( isset($_GET) and isset($_GET['edit']) and ! empty( $_GET['note_id'] ) ) {
	get_header("Edit note", "Edit this note");
	$note_id = htmlspecialchars( $_GET['note_id'], ENT_QUOTES );
	
	$note_details = get_note_details( $note_id, "to_edit" );
	
	if ( $note_details['fail'] == "fail" ) {
		die( json_encode( $note_details ) );
	}
	
	if ( $note_details['pass'] == "pass" ) {
		$note_details = $note_details["note_details"];
	}
	
	if ( count( $note_details ) > 0 ) {
		$note_privacy = ( ( $note_details['note_privacy'] == "private" ) ? "checked=checked" : "" );
		
		# if private note, keep the box checked. let the user change it if needed.		
		echo sprintf('
		<div id="modal_create_note">
			<form action="#" method="POST" id="form_edit_note"><input name="note_id" type="hidden" value="%s">
				<div class="note_title_wrap">
					<div class="sub_heading"> Note title: </div>
					<input value="%s" required="required" type="text" name="note_title" id="note_title" autocomplete="off" maxlength="256" size="56" placeholder="Note title. Preferably a crispy one!">
				</div>
				<div class="sub_heading"> Note content: </div>
				<textarea class="note_content" name="content">%s</textarea>
				
				<div class="sub_heading">Private note? Yes.<input type="checkbox" title="If checked, then this note will be visible ONLY to you. Otherwise, to everyone!" name="note_privacy" id="note_privacy" %s>
				</div>
							
				<div id="tags">
					<div class="sub_heading">Tags: (comma separated) </div>
					<input required="required" type="text" name="note_tags" id="note_tags" autocomplete="off" maxlength="256" size="56" placeholder="Tags for this note. Comma seperated." value="%s">
				</div>
				
				<input type="button" id="submit_edits" value="Save edits">
				<a href="%s" class="button_mainpage"><input type="button" value="Done editing"></a>				
			</form>
			<script type="text/javascript">
			tinymce.triggerSave();
			</script>
			<div id="response"></div></div>',
					  $note_id,
					  $note_details['note_title'],
					  $note_details['note_content'],					  
					  $note_privacy,
					  $note_details['note_tags'],
					  this_page_url()
		);
	}
	get_footer();
}

if ( isset($_GET) and isset($_GET['delete']) and ! empty( $_GET['note_id'] ) ) {
	$note_id = htmlspecialchars( $_GET['note_id'], ENT_QUOTES );
	$delete_note_response = delete_note($note_id);
	echo json_encode($delete_note_response);
}

if ( isset( $_GET['save_edits'] ) and ! empty ( $_POST ) ) {	
		//echo var_dump($_POST);
		$note_id = htmlspecialchars( $_POST['note_id'], ENT_QUOTES );
		if ( ! is_author ( $note_id ) ) {
			echo "<div>You are unauthorized to edit this note! If you are sure you own this note, refresh the page, and try editing.</div>";
			die();
		}
		# all set. this guy owns the note. So, he can edit it.
		
		$note_author = get_note_author( $note_id );
		$note_title = htmlspecialchars( $_POST['note_title'], ENT_QUOTES );
		$note_content = $_POST['content'];
		$note_tags = ( empty ($_POST['note_tags']) ) ?  "" : htmlspecialchars( $_POST['note_tags'], ENT_QUOTES );
		$note_privacy = ( empty ($_POST['note_privacy']) ) ?  "public" : "private";
		
		
		try {
			$pdo = open_connection_pdo();	
			$stmnt = $pdo->prepare("UPDATE NOTES SET note_title=:note_title, note_content=:note_content, note_author=:note_author, note_privacy=:note_privacy, note_tags=:note_tags WHERE note_id=:note_id");
			
			$stmnt->bindParam(":note_id", $note_id);
			$stmnt->bindParam(":note_title", $note_title);
			$stmnt->bindParam(":note_content", $note_content);
			$stmnt->bindParam(":note_author", $note_author);
			$stmnt->bindParam(":note_privacy", $note_privacy);
			$note_tags = preg_replace('/\s+,\s+/' , ',', $note_tags); # replace <comma><space> with just a <comma>
			$stmnt->bindParam(":note_tags", $note_tags);
		
			$result = $stmnt->execute();
			
		} catch( PDOException $e ) {
			array_push( $errors, sprintf("Internal Error: Could not save the note to database: %s", $e->getMessage() ) );
		}
		
		echo '<div id="success"> Updated! </div>';
}

if ( isset( $_GET['my_notes'] ) and count($_GET) == 1 ) {
	get_header("My notes(all)","My notes (All)");
	
	$notes = get_notes("my_notes");
	if ( count($notes) == 0 ) {
		echo '<div id="noresults">You have not written any notes yet.</div>';
	} else {
		echo htmlize_notes( $notes, "all_notes" );		
	}
	
	get_footer();
}

if ( isset( $_GET['my_private_notes'] ) and count($_GET) == 1  ) {
	get_header("My private notes", "My private notes.");
	$notes = get_notes("my_private_notes");
	
	if ( count($notes) == 0 ) {
		echo '<div id="rack">
		<div id="noresults">You do not have any private notes.</div>
		</div>';	
	} else {
		echo htmlize_notes($notes, "my_private_notes" );	
	}
	
	get_footer();
}

if ( isset( $_GET['my_public_notes'] ) and count($_GET) == 1 ) {
	get_header("My public notes", "My public notes");
	$notes = get_notes("my_public_notes");
	
	if ( count($notes) == 0 ) {
		echo '<div id="noresults">You do not have any public notes.</div>';		
	} else {
		echo htmlize_notes( $notes, "my_public_notes" );
	}
	
	get_footer();
}

if ( ! empty ( $_GET['tag'] ) and isset( $_GET['all_notes'] ) and count($_GET) == 2 ) {
		
	$tag = htmlspecialchars( $_GET['tag'], ENT_QUOTES );
	get_header( sprintf( "All notes tagged with: %s", $tag), sprintf( "All notes tagged with: %s", $tag) );
	
	$notes = get_notes_by_tag ( $tag, 'all_notes' );
	echo htmlize_notes( $notes, "all_notes" );
	
	get_footer();
}


if ( ! empty ( $_GET['tag'] ) and isset( $_GET['my_public_notes'] ) and count($_GET) == 2 ) {
		
	$tag = htmlspecialchars($_GET['tag'], ENT_QUOTES);
	get_header( sprintf( "Public notes tagged with: %s", $tag), sprintf( "Public notes tagged with: %s", $tag) );
	
	$notes = get_notes_by_tag ( $tag, 'my_public_notes' );
	echo htmlize_notes( $notes, "my_public_notes" );
	
	get_footer();
}


if ( ! empty ( $_GET['tag'] ) and isset( $_GET['my_notes'] ) and count($_GET) == 2 ) {
	get_header(sprintf( "My notes tagged with: %s", $tag),"");
		
	$tag = htmlspecialchars( $_GET['tag'], ENT_QUOTES );
	
	$notes = get_notes_by_tag ( $tag, 'my_notes' );
	echo sprintf('<div id="header_sub_title"> %s </div>', "Tagged with <strong>$tag</strong> (My notes)" );
	echo htmlize_notes( $notes, "my_notes" );
	
	get_footer();
}


if ( ! empty ( $_GET['tag'] ) and isset( $_GET['my_private_notes'] ) and count($_GET) == 2  ) {
	get_header( sprintf( "My private notes tagged with: %s", $tag ), sprintf( "My private notes tagged with: %s", $tag ));
	
	$tag = htmlspecialchars( $_GET['tag'], ENT_QUOTES );
	
	$notes = get_notes_by_tag ( $tag, 'my_private_notes' );
	echo htmlize_notes( $notes, "my_private_notes" );
	
	get_footer();
}
  
if ( ! empty ( $_GET['author'] ) and count($_GET) == 1 ) {
		
	$author = htmlspecialchars( $_GET['author'], ENT_QUOTES );
	get_header( sprintf( "Notes owned by: %s", $author), sprintf( "Notes owned by: %s", $author));
	
	$notes = get_notes_by_author ( $author );
	echo htmlize_notes( $notes, "all_notes" );
	
	get_footer();
}


if ( isset ( $_GET['load_suggestions'] ) and ! empty ( $_GET['for_title'] ) and ( count($_GET) == 2 ) ) {
	$suggestions = get_suggestions( "by_note_title", $_GET['for_title'], 5 );
	asort($suggestions);
	
	if ( count($suggestions) > 0 ) {
		foreach ( $suggestions as $note_id => $matching_words ) {
			echo sprintf('<div> <a href="%s" class="suggested_note" target="_blank">%s</a></div>', 
			get_note_url($note_id), get_note_title($note_id) );
		}		
	}
}

if ( isset ( $_GET['comments'] ) and ! empty ( $_GET['note_id'] ) and ( count($_GET) == 2 ) ) {
	$note_id = $_GET['note_id'];
	echo '<div id="comments_dialogue"><h3>Comment or Suggest corrections</h3>';
	echo sprintf('%s %s', get_comments( $note_id ), get_comments_form($note_id) );
	echo '</div>';
}

if ( isset ( $_GET['write_comment'] ) ) {
	
	$response = array();
	if ( ! isset( $_POST['note_id'] ) or empty ( $_POST['note_id'] ) ) {
		$response["error_text"] = "Don't know the note for which the comment was sent. Something broke!<br>";
		$response["errors"] = 1;
	}
	
	if ( ! isset( $_POST['comment_text'] ) or empty ( $_POST['comment_text'] ) ) {
		$response["error_text"] = "Comment content has to filled up!<br>";
		$response["errors"] = 1;
	}
	
	if ( isset ($response["errors"] ) ) {
		die ( json_encode($response) );
	}
	
	$note_id = htmlspecialchars( $_POST['note_id'] );
	$comment_text = htmlspecialchars( $_POST['comment_text'] );
	$comment_author = ( logged_in() ? get_user_id ( $_SESSION['username'] ) : -1 );
	$comment_author_name = ( logged_in() ? $_SESSION['username']  : "anonymous" );
		
	date_default_timezone_set('GMT');
		
	$comment_time = date("Y-m-d H:i:s");
	
	try {
		$pdo = open_connection_pdo();
		$stmnt = $pdo->prepare("INSERT INTO comments( note_id, comment_text, comment_author, commented_at ) VALUES( :note_id, :comment_text, :comment_author, :comment_time)");
			
		$stmnt->bindParam(":note_id", $note_id);
		$stmnt->bindParam(":comment_text", $comment_text);
		$stmnt->bindParam(":comment_author", $comment_author);
		$stmnt->bindParam(":comment_time", $comment_time);

		$pdo->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
		$pdo->setAttribute( PDO::ATTR_EMULATE_PREPARES, false ); 
			
		$stmnt->execute();
		
	} catch( PDOException $e ) {
		echo sprintf( "Errors: %s", $e->getMessage() );
		die();
	}

	$response["success"] = 1;
	$response["inserted_comment"] = sprintf('<tr><td class="comment_author">%s: </td><td class="comment_text">%s</td> <td class="comment_time">%s</td></tr>', $comment_author_name, $comment_text, $comment_time );
	
	echo json_encode($response);
}
?>





